﻿using FemtoHttpd;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;

namespace HttpFileServer
{
    class SSLManager : ISSLEngine
    {
        X509Certificate serverCertificate = null;
        public SSLManager(string certConfigFile)
        {
            try
            {
                var lines = File.ReadAllLines(certConfigFile);
                serverCertificate = new X509Certificate(lines[0], lines[1]);
            }
            catch (Exception)
            {
                MessageBox.Show("证书配置信息不存在，请配置 cert.config 文件！");
                var lines = new string[] { "PKCS7 signed file path","password" };
                File.WriteAllLines(certConfigFile,lines);
                Environment.Exit(0);
            }

        }
        public SSLManager(string certificate, string password)
        {
            serverCertificate = new X509Certificate(certificate, password);
        }

        public SslStream CreateSslStream(Stream stream)
        {
            SslStream sslStream = new SslStream(stream, false, (s, cert, chain, err) =>
            {
                //Trace.WriteLine(cert.Subject);
                // if (err == SslPolicyErrors.None)
                //    return true;
                //  Console.WriteLine("Certificate error: {0}", err);
                return true;// Do not allow this client to communicate with unauthenticated servers.
            });
            sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls12, true);
            sslStream.ReadTimeout = 5000;
            sslStream.WriteTimeout = 5000;
            return sslStream;
        }
    }
}
